<?php

namespace app\system\service;


use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class AuthService
{
    public function login($data): \think\response\Json|array
    {
        try {
            // 参数验证
            $validate = new \think\Validate();
            //规则
            $validate->rule([
                'username' => 'require|length:3,30',
                'password' => 'require|length:3,30',
//            '__token__' => 'require|token',
            ]);
            if (!$validate->check($data)) {
                return json(['success' => false, 'info' => $validate->getError()]);
            }
            // 验证用户名和密码
            $validateRes = LoginService::validateAccount($data['username'], $data['password']);

            if ($validateRes['success'] !== true) {
                throw new \Exception($validateRes['info']);
            }
            // 用户存在且密码正确，生成token
            $accessToken = (new TokenService())->generateToken($validateRes['data']['id']);

            //刷新token
            $refreshToken = (new TokenService())->generateToken($validateRes['data']['id'], 'refresh');
            $decoded = JWT::decode($accessToken, new Key(md5(config('jwt.salt')), 'HS256'));

            return json([
                'success' => true,
                'info' => '登录成功',
                'data' => [
                    'username' => 'admin',
                    'nickname' => 'admin',
                    'roles' => isset($validateRes['data']['roles'])?explode(",",$validateRes['data']['roles']):[], // 这里的角色应该基于用户实际的角色进行设置
                    'accessToken' => $accessToken,
                    'refreshToken' => $refreshToken,
                    'expires' => date("Y/m/d H:i:s", $decoded->exp)
                ]
            ]);
        } catch (\Exception $e) {
            return json(['success' => false, 'info' => $e->getMessage()]);
        }
    }



}